package com.pubinfo.passbook.common.service.request.financial.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.pubinfo.passbook.common.config.ApplicationConfig;
import com.pubinfo.passbook.common.entity.*;
import com.pubinfo.passbook.common.mapper.TSubsidiaryPrivateKeyMapper;
import com.pubinfo.passbook.common.model.bo.SubsidiaryInfo;
import com.pubinfo.passbook.common.model.constant.LogNameEnum;
import com.pubinfo.passbook.common.model.dto.financial.*;
import com.pubinfo.passbook.common.service.master.*;
import com.pubinfo.passbook.common.service.request.financial.RequestFinancialServer;
import com.pubinfo.passbook.common.utils.financial.CommonTestUtils;
import com.pubinfo.passbook.common.utils.tax.Util;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RequestFinancialServerImpl implements RequestFinancialServer {
  @Autowired
  private TSyncLogService kafkaSender;
  @Resource
  private ApplicationConfig config;
  
  @Autowired
  TSystemTaskLogService taskLogService;
  
  @Autowired
  private TSubsidiaryPrivateKeyMapper keyMapper;
  @Autowired
  TPassbookService passbookService;
  
  @Autowired
  TSourcePassbookReimburseService reimburseService;
  
  @Autowired
  TPassbookClaimFeedbackService claimFeedbackService;
  @Autowired
  TSubsidiaryInfoService infoService;
  @Autowired
  TInvoiceService tInvoiceService;

  @Override
  public List<String> checkFinancial(String id) {
    List<SubsidiaryInfo> infoList = keyMapper.listFinAllSubsidiaryInfo(id);
    String startDate = Util.getFinancialOnTheDay();
    List<String> names = new ArrayList<>();
    if (!CollectionUtils.isEmpty(infoList)) {
      for (SubsidiaryInfo info : infoList) {
        JSONObject payloadObject = new JSONObject();
        payloadObject.put("startDate", startDate);
        payloadObject.put("endDate", startDate);
        String url = config.getFinancial().getApi().getBillList();
        TRequestLog syncLog = new TRequestLog();
        syncLog.setUrl(url).setParam(payloadObject.toJSONString()).setType(0).setName(LogNameEnum.BILL.getCode());
        String responseStr = post(info, url, payloadObject, syncLog, 0);
        InvoiceResult<TPassbook> pageResult = (InvoiceResult<TPassbook>) JSONObject.parseObject(responseStr, InvoiceResult.class);
        if (pageResult == null || !pageResult.getSuccess()) {
          names.add(info.getName());
        }
      }
    }
    return names;
  }

  @Override
  public InvoiceResult<JSONObject> invoiceDetailList(JSONObject json)
  {
    String regex = "[\\\"' ]*[^:\\\"' ]*[\\\"' ]*:";// (\{|\,)[a-zA-Z0-9_]+:
    Pattern pattern = Pattern.compile(regex);
    StringBuffer sb = new StringBuffer();
    Matcher m = pattern.matcher(json.toJSONString());
    while (m.find()) {
      m.appendReplacement(sb, m.group().toLowerCase());
    }
    m.appendTail(sb);
    JSONObject jsonObject=JSONObject.parseObject(sb.toString().replaceAll("\\\\","\\\\\\\\").replaceAll("\\\\\\\\r","\\\\r").replaceAll("\\\\\\\\n","\\\\n"));
    Date kprq=jsonObject.getDate("kprq");
    jsonObject.put("kprq", DateUtil.format(kprq, "yyyy-MM-dd"));
    JSONArray jsonArray=jsonObject.getJSONArray("items");
    for(int i=0;i<jsonArray.size();i++){
      // 遍历 jsonarray 数组，把每一个对象转成 json 对象
      JSONObject insertObj = jsonArray.getJSONObject(i);
      try {
        kprq=insertObj.getDate("kprq");
        insertObj.put("kprq", DateUtil.format(kprq, "yyyy-MM-dd"));
      } catch (Exception e) {
      }
    }
    List<JSONObject> jsonObjects=new ArrayList<>();
    jsonObjects.add(jsonObject);
    return new InvoiceResult<>(jsonObjects);
  }


  @Override
  public InvoiceResult detailsByParam(QueryDetailsParam detailsParam) {
    InvoiceResult<Result> invoiceResult = new InvoiceResult<>("INVOICE_NOT_EXIST", "没有找到该票据");
    InvoiceResult<Result> invoiceResult2 = new InvoiceResult<>("INVOICE_NOT_EXIST", "没有找到该发票");
    if ("19".equals(detailsParam.getEInvoiceType())) {
      QueryWrapper<TPassbook> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("eInvoice_code", detailsParam.getInvoiceCode());
      queryWrapper.eq("eInvoice_number", detailsParam.getInvoiceNumber());
      List<TPassbook> passbookList = passbookService.list(queryWrapper);
      if (CollectionUtils.isEmpty(passbookList)) {
        return invoiceResult;
      }
      String eInvoiceId = passbookList.get(0).getEInvoiceId();
      if (StringUtils.isEmpty(eInvoiceId)) {
        return invoiceResult;
      }
      return detailList(eInvoiceId);
    }
    //发票校验
    else if("20".equals(detailsParam.getEInvoiceType()))
    {
      QueryWrapper<TSourceInvoice> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("fpdm", detailsParam.getInvoiceCode());
      queryWrapper.eq("fphm", detailsParam.getInvoiceNumber());
      List<TSourceInvoice> passbookList = tInvoiceService.list(queryWrapper);
      if (CollectionUtils.isEmpty(passbookList)) {
        return invoiceResult2;
      }
      return invoiceDetailList(passbookList.get(0).getDataJson());
    }
    return invoiceResult;
  }
  
  @Override
  public Boolean checkId(List<String> eInvoiceIds) {

    List<TPassbook> tPassbookList=new ArrayList<>();
    if(CollectionUtils.isNotEmpty(eInvoiceIds))
    {
      tPassbookList=passbookService.getPassbookById(eInvoiceIds);
    }
    if (CollectionUtils.isEmpty(tPassbookList)) {
      return false;
    }
    List<TPassbook> newList = tPassbookList.stream().collect(Collectors
        .collectingAndThen(
            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TPassbook::getNsrsbh))),
            ArrayList::new));
    return newList.size() <= 1;
  }
  
  public Integer subsidiaryBillList(String startDate, String endDate) {
    List<SubsidiaryInfo> infoList = keyMapper.listFinAllSubsidiaryInfo(null);
    if (CollectionUtils.isEmpty(infoList)) {
      return 0;
    }
    Integer count = 0;
    for (SubsidiaryInfo info : infoList) {
      count += billList(info, startDate, endDate, true).size();
    }
    return count;
  }
  
  @Transactional
  @SneakyThrows
  public List<TPassbook> billList(SubsidiaryInfo info, String startDate, String endDate, Boolean isSave) {
    JSONObject payloadObject = new JSONObject();
    payloadObject.put("startDate", startDate);
    payloadObject.put("endDate", endDate);
    //331023200011111111
    TTaskLog systemTaskLog = new TTaskLog(startDate, endDate);
    String url = config.getFinancial().getApi().getBillList();
    TRequestLog syncLog = new TRequestLog();
    syncLog.setUrl(url).setParam(payloadObject.toJSONString()).setType(0).setName(LogNameEnum.BILL.getCode());
    List<TPassbook> passbooks = new ArrayList<>();
    String responseStr = post(info, url, payloadObject, syncLog, 0);
    JSONObject jsonObject = JSONObject.parseObject(responseStr);
    InvoiceResult<TPassbook> pageResult = (InvoiceResult<TPassbook>) JSONObject.parseObject(responseStr, InvoiceResult.class);
    if (StringUtils.isEmpty(pageResult) || !pageResult.getSuccess()) {
      syncLog.setStatus(1);
      kafkaSender.saveOrUpdate(syncLog);
      return passbooks;
    }
    log.info(startDate + "-" + endDate + info.getName() + ":" + info.getNsrsbh() + "接收总条数:" + pageResult.getResult().size());
    systemTaskLog.setAcceptTotalCount(pageResult.getResult().size());
    //记录下载接口查询到的数据,因为会被锁住;
    passbooks = JSON.parseArray(jsonObject.getString("result"), TPassbook.class);
    if (isSave) {
      systemTaskLog.setTaskId("2");
      systemTaskLog.setId(IdWorker.get32UUID());
      taskLogService.save(systemTaskLog);
      StringBuilder passbookIds = new StringBuilder();
      passbooks.stream().forEach(
          passbook -> {
            passbook.setLogId(systemTaskLog.getId());
            passbook.setNsrsbh(info.getNsrsbh());
            passbookIds.append(passbook.getEInvoiceId() + ",");
          });
      syncLog.setStatus(2);
      syncLog.setRemark(passbookIds.toString());
      kafkaSender.saveOrUpdate(syncLog);
      passbooks = setJson(passbooks, info);
      List<TPassbook> insertList = null;
      if (!CollectionUtils.isEmpty(passbooks)) {
        QueryWrapper<TPassbook> queryWrapper = new QueryWrapper<>();
        List<String> sourceList = passbooks.stream().map(TPassbook::getEInvoiceId).collect(Collectors.toList());
        queryWrapper.select("e_invoice_id").in("e_invoice_id", sourceList);
        List<TPassbook> queryPassbooks = passbookService.list(queryWrapper);
        //取源数据与查询数据的差集
        List<String> dbList = queryPassbooks.stream().map(TPassbook::getEInvoiceId).collect(Collectors.toList());
        sourceList.removeAll(dbList);
        insertList = passbooks.stream().filter(e -> sourceList.contains(e.getEInvoiceId())).collect(Collectors.toList());
      } else {
        insertList = passbooks;
      }
      passbookService.saveBatch(insertList);
      saveReimburse(insertList, systemTaskLog.getId(), info);
    }
    
    return passbooks;
  }
  
  private void saveReimburse(List<TPassbook> passbooks, String logId, SubsidiaryInfo info) {
    if (!CollectionUtils.isEmpty(passbooks)) {
      
      //保存报销记录 如果有数据,则直接保存,否则直接更新
      passbooks.stream().forEach(passbook -> {
        //如果查询出来有数据,先删除,再新增
        //没有数据,不操作
        passbook.setLogId(logId);
        List<TSourcePassbookReimburse> reimburseList = passbook.getReimburseList();
        if (!CollectionUtils.isEmpty(reimburseList)) {
          QueryWrapper<TSourcePassbookReimburse> queryWrapper = new QueryWrapper<>();
          queryWrapper.eq("e_invoice_id", passbook.getEInvoiceId());
          reimburseService.remove(queryWrapper);
          reimburseService.saveBatch(reimburseList);
        }
      });
    }
  }
  
  @Override
  public List<TPassbook> subsidiaryBillList(String startDate, String endDate, String nsrsbh) {
  
    List<ImmutablePair<String, String>> pairList = Util.getFinancialTwoDaysDay(startDate, endDate);
    List<TPassbook> passbooks = new ArrayList<>();
    List<SubsidiaryInfo> subsidiaryInfos = keyMapper.listFinAllSubsidiaryInfo(nsrsbh);
    if (!CollectionUtils.isEmpty(pairList)) {
      for (ImmutablePair<String, String> pair : pairList) {
        passbooks.addAll(billList(subsidiaryInfos.get(0), pair.getLeft(), pair.getRight(), false));
  
      }
    }
    return passbooks;
  }
  
  @Override
  public InvoiceResult<Result> detailList(String eInvoiceId) {
    List<String> eInvoiceIds = new ArrayList<>();
    eInvoiceIds.add(eInvoiceId);
    QueryWrapper<TPassbook> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("e_invoice_id", eInvoiceId);
    List<TPassbook> passbooks = passbookService.list(queryWrapper);
    //  TPassbook passbook = passbookService.getById(eInvoiceId);
    List<SubsidiaryInfo> subsidiaryInfos = keyMapper.listFinAllSubsidiaryInfo(passbooks.get(0).getNsrsbh());
    if (CollectionUtils.isEmpty(subsidiaryInfos)) {
      return new InvoiceResult<Result>();
    }
    return detailList(eInvoiceIds, subsidiaryInfos.get(0));
  }
  
  @Override
  public List<TPassbook> setJson(List<TPassbook> medicalList, SubsidiaryInfo info) {
    List<TPassbook> batchList = new ArrayList<>();
    if (!CollectionUtils.isEmpty(medicalList)) {
      Integer maxCount = 20;
      Integer total = medicalList.size();
      Integer totalPage = (total + maxCount - 1) / maxCount;
      for (int i = 1; i <= totalPage; i++) {
        //限制20条
        List<TPassbook> itemList = medicalList.stream().skip((i - 1) * maxCount).limit(maxCount).collect(Collectors.toList());
        List<Result> resultList = findResultByIds(itemList, info);
        if (!CollectionUtils.isEmpty(resultList)) {
          itemList.stream().forEach(tPassbook -> {
            //设置json
            Result result = resultList.stream().filter(e -> e.getEinvoiceId().equals(tPassbook.getEInvoiceId())).findFirst().get();
            // tPassbook.setDataJson(XmlTool.xml2json(result.getEinvoiceXML()));
            //设置详情数据
            tPassbook.setResult(result);
          });
        }
        
        //  List<TPassbook> notReimburseList = filterReimburse(resultList, itemList);
        //如果没有查到票据报销记录,则保存,否则不处理
        batchList.addAll(itemList);
        //  saveBatch(notReimburseList);
      }
      
    }
    return batchList;
  }
  
  public List<Result> findResultByIds(List<TPassbook> itemList, SubsidiaryInfo info) {
    List<String> medicalIdList = itemList.stream().map(TPassbook::getEInvoiceId).collect(Collectors.toList());
    InvoiceResult<Result> invoiceResult = detailList(medicalIdList, info);
    return invoiceResult.getResult();
  }
  
  @Override
  @Transactional
  public InvoiceResult<Result> detailList(List<String> eInvoiceIds, SubsidiaryInfo info, Integer pdfType) {
    JSONObject payloadObject = new JSONObject();
    payloadObject.put("eInvoiceIds", eInvoiceIds);
    payloadObject.put("pdfType", pdfType);
    TRequestLog syncLog = new TRequestLog();
    String url = config.getFinancial().getApi().getDetailList();
    syncLog.setType(0).setParam(payloadObject.toJSONString()).setUrl(url).setStatus(2).setName(LogNameEnum.DETAIL.getCode()).setRemark(info.getNsrsbh());
    // String responseStr = CommonTestUtils.post(url , params);
    String responseStr = post(info, url, payloadObject, syncLog, 0);
    InvoiceResult<Result> pageResult = JSONObject.parseObject(responseStr, InvoiceResult.class);
    //数组类型,直接转换再取出会报错.
    JSONObject jsonObject = JSONObject.parseObject(responseStr);
    List<Result> resultList = JSON.parseArray(jsonObject.getString("result"), Result.class);
    //对xml数据进行bese64解码
    if (!CollectionUtils.isEmpty(resultList)) {
      resultList.stream().forEach(result -> {
        String einvoiceXML = result.getEinvoiceXML();
        String xml = null;
        xml = new String(Base64.getDecoder().decode(einvoiceXML), StandardCharsets.UTF_8);
        result.setEinvoiceXML(xml);
      });
    }
  
    pageResult.setResult(resultList);
    return pageResult;
  }
  
  @Override
  @Transactional
  public InvoiceResult<Result> detailList(List<String> eInvoiceIds, SubsidiaryInfo info) {
    JSONObject payloadObject = new JSONObject();
    payloadObject.put("eInvoiceIds", eInvoiceIds);
    payloadObject.put("pdfType", 1);
    TRequestLog syncLog = new TRequestLog();
    String url = config.getFinancial().getApi().getDetailList();
    syncLog.setType(0).setParam(payloadObject.toJSONString()).setUrl(url).setStatus(2).setName(LogNameEnum.DETAIL.getCode()).setRemark(info.getNsrsbh());
    // String responseStr = CommonTestUtils.post(url , params);
    String responseStr = post(info, url, payloadObject, syncLog, 0);
    InvoiceResult<Result> pageResult = JSONObject.parseObject(responseStr, InvoiceResult.class);
    //数组类型,直接转换再取出会报错.
    JSONObject jsonObject = JSONObject.parseObject(responseStr);
    List<Result> resultList = JSON.parseArray(jsonObject.getString("result"), Result.class);
    //对xml数据进行bese64解码
    if (!CollectionUtils.isEmpty(resultList)) {
      resultList.stream().forEach(result -> {
        String einvoiceXML = result.getEinvoiceXML();
        String xml = null;
        xml = new String(Base64.getDecoder().decode(einvoiceXML), StandardCharsets.UTF_8);
        result.setEinvoiceXML(xml);
      });
    }
    
    pageResult.setResult(resultList);
    return pageResult;
  }
  
  @Transactional
  @Override
  public InvoiceResult<Object> cancelLockedList(List<CancelLockedRecord> cancelLockedRecords, String reason) {
    List<String> eInvoiceIdList = cancelLockedRecords.stream().map(CancelLockedRecord::getEInvoiceId).collect(Collectors.toList());
    if (!checkId(eInvoiceIdList)) {
      return null;
    }
    JSONObject payloadObject = new JSONObject();
    TRequestLog syncLog = new TRequestLog();
    payloadObject.put("reason", reason);
    payloadObject.put("cancelLockedRecords", cancelLockedRecords);
    SubsidiaryInfo info = keyMapper.listFinSubsidiaryInfoByEinvoiceId(eInvoiceIdList.get(0));
    
    String url = config.getFinancial().getApi().getCancelLockedList();
    syncLog.setType(0).setParam(payloadObject.toJSONString()).setUrl(url).setStatus(2).setName(LogNameEnum.CANCEL_LOCKED.getCode());
    String responseStr = post(info, url, payloadObject, syncLog, 0);
    InvoiceResult<Object> pageResult = JSONObject.parseObject(responseStr, InvoiceResult.class);
//    syncLog.setData(JSONObject.toJSONString(pageResult));
  
    return pageResult;
  }
  
  @Override
  public Boolean lockedByEinvoiceId(String eInvoiceId) {
    /*
    先查询票据详情,再通过开票日期,通过下载接口,实现锁定
     */
    if (StringUtils.isEmpty(eInvoiceId)) {
      return false;
    }
    InvoiceResult<Result> results = detailList(eInvoiceId);
    if (results.getSuccess()) {
      Result result = results.getResult().get(0);
      if (result != null) {
        String issueDate = result.getIssueDate();
        SubsidiaryInfo info = keyMapper.listFinSubsidiaryInfoByEinvoiceId(eInvoiceId);
        
        List<TPassbook> passbooks = billList(info, issueDate, issueDate, false);
        //等待10秒钟再进行解锁其他的数据.
        if (CollectionUtils.isEmpty(passbooks)) {
          return false;
        }
        try {
          Thread.sleep(10000L);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        List<String> eInvoiceIds = passbooks.stream().filter(passbook -> !passbook.getEInvoiceId().equalsIgnoreCase(eInvoiceId)).map(TPassbook::getEInvoiceId).collect(Collectors.toList());
        List<CancelLockedRecord> cancelLockedRecords = CancelLockedRecord.toList(eInvoiceIds);
        InvoiceResult<Object> invoiceResult = cancelLockedList(cancelLockedRecords, "取消");
        return invoiceResult.getSuccess();
        
      }
      
    }
    return false;
  }
  
  @Override
  public Integer syncAll(String startDate, String endDate) {
    //分割日期,每段不超过七天
    List<ImmutablePair<String, String>> pairList = Util.getFinancialTwoDaysDay(startDate, endDate);
    Integer count = 0;
    if (!CollectionUtils.isEmpty(pairList)) {
      for (ImmutablePair<String, String> pair : pairList) {
        count += subsidiaryBillList(pair.getLeft(), pair.getRight());
      }
    }
    return count;
  }
  
  @Override
  public Boolean cancelClaimFeed(CancelClaimFeed cancelClaimFeed) {
    JSONObject payloadObject = new JSONObject();
    payloadObject.put("accNumber", cancelClaimFeed.getAccNumber());
    payloadObject.put("accDate", cancelClaimFeed.getAccDate());
    payloadObject.put("reason", cancelClaimFeed.getReason());
    TRequestLog syncLog = new TRequestLog();
    QueryWrapper<TPassbookClaimFeedback> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("acc_number", cancelClaimFeed.getAccNumber());
    queryWrapper.eq("acc_date", cancelClaimFeed.getAccDate());
    TPassbookClaimFeedback feedback = claimFeedbackService.getOne(queryWrapper);
    SubsidiaryInfo info = keyMapper.listFinSubsidiaryInfoByEinvoiceId(feedback.getEInvoiceId());
    
    String url = config.getFinancial().getApi().getCancelClaimFeed();
    syncLog.setType(0).setParam(payloadObject.toJSONString()).setUrl(url).setStatus(2).setName(LogNameEnum.CANCEL_CLAIM_FEED.getCode());
    String responseStr = post(info, url, payloadObject, syncLog, 0);
    InvoiceResult<Object> pageResult = JSONObject.parseObject(responseStr, InvoiceResult.class);
  
    return pageResult.getSuccess();
  }
  
  @Override
  public void sync(String taskId) {
    //取当天的数据.
    String startDate = Util.getFinancialOnTheDay();
    subsidiaryBillList(startDate, startDate);
  }
  
  /**
   * 一次只报销一条
   *
   * @param feedbackParam
   * @return
   */
  @Override
  public Boolean claimFeedback(FeedbackParam feedbackParam) {
    List<String> eInvoiceIdList = feedbackParam.getClaimRecords().stream().map(ClaimRecord::getEInvoiceId).collect(Collectors.toList());
    if (!checkId(eInvoiceIdList)) {
      return false;
    }
    JSONObject payloadObject = new JSONObject();
    payloadObject.put("accNumber", feedbackParam.getAccNumber());
    payloadObject.put("accDate", feedbackParam.getAccDate());
    payloadObject.put("claimRecords", feedbackParam.getClaimRecords());
    TRequestLog syncLog = new TRequestLog();
    SubsidiaryInfo info = keyMapper.listFinSubsidiaryInfoByEinvoiceId(eInvoiceIdList.get(0));
    
    String url = config.getFinancial().getApi().getClaimFeedback();
    syncLog.setType(0).setParam(payloadObject.toJSONString()).setUrl(url).setStatus(2).setName(LogNameEnum.CLAIM_FEEDBACK.getCode());
    String responseStr = post(info, url, payloadObject, syncLog, 0);
    InvoiceResult<Object> pageResult = JSONObject.parseObject(responseStr, InvoiceResult.class);
    //一次只报销一条
    TPassbookClaimFeedback feedback = new TPassbookClaimFeedback(feedbackParam);
  
    claimFeedbackService.save(feedback);
    return pageResult.getSuccess();
  }
  
  public String post(SubsidiaryInfo info, String url, JSONObject json, TRequestLog syncLog) {
    url = config.getFinancial().getUrl() + url;
    String obj = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-type", "application/json; charset=utf-8");
    httppost.setHeader("Accept", "application/json");
    try {
      //   log.info("请求json参数" + json);
      String params = CommonTestUtils.getRequestParams(info.getNsrsbh(), info.getPrivateKey(), info.getPassword(), json);
      StringEntity s = new StringEntity(params, StandardCharsets.UTF_8);  //对参数进行编码，防止中文乱码
      s.setContentEncoding("UTF-8");
      httppost.setEntity(s);
      try (CloseableHttpResponse response = httpclient.execute(httppost)) {
        //获取相应实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
          obj = EntityUtils.toString(entity, "UTF-8");
        }
        // log.info("接收参数\r\n" + obj);
        InvoiceResult<Object> pageResult = JSONObject.parseObject(obj, InvoiceResult.class);
        syncLog.setData(JSONObject.toJSONString(pageResult));
  
        if (StringUtils.isEmpty(pageResult) || pageResult.getSuccess() == null || !pageResult.getSuccess()) {
          syncLog.setStatus(0);
          kafkaSender.save(syncLog);
          //  throw new ServiceException(syncLog.getName() + "失败:数据:" + JSON.toJSONString(pageResult));
        }
        kafkaSender.saveOrUpdate(syncLog);
      }
    } catch (Exception e) {
  
    } finally {
      try {
        httpclient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return obj;
  }
  
  public String post(SubsidiaryInfo info, String url, JSONObject json, TRequestLog syncLog, Integer count) {
    url = config.getFinancial().getUrl() + url;
    String obj = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-type", "application/json; charset=utf-8");
    httppost.setHeader("Accept", "application/json");
    try {
      
      String params = CommonTestUtils.getRequestParams(info.getNsrsbh(), info.getPrivateKey(), info.getPassword(), json);
      StringEntity s = new StringEntity(params, StandardCharsets.UTF_8);  //对参数进行编码，防止中文乱码
  
      s.setContentEncoding("UTF-8");
      httppost.setEntity(s);
      try (CloseableHttpResponse response = httpclient.execute(httppost)) {
        //获取相应实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
          obj = EntityUtils.toString(entity, "UTF-8");
        }
        // log.info("接收参数\r\n" + obj);
        InvoiceResult<Object> pageResult = JSONObject.parseObject(obj, InvoiceResult.class);
        syncLog.setData(JSONObject.toJSONString(pageResult));
        
        if (StringUtils.isEmpty(pageResult) || pageResult.getSuccess() == null || !pageResult.getSuccess()) {
          syncLog.setStatus(0);
          kafkaSender.save(syncLog);
          //  throw new ServiceException(syncLog.getName() + "失败:数据:" + JSON.toJSONString(pageResult));
        }
        //  kafkaSender.saveOrUpdate(syncLog);
      }
    } catch (Exception e) {
      //重试五次
      count++;
      if (count <= 5) {
        post(info, url, json, syncLog, count);
      }
    } finally {
      try {
        httpclient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return obj;
  }
  
}
